package app;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.Vector;

import org.w3c.dom.Element;

import utils.HttpItem;
import utils.HttpItemListener;
import utils.HttpQueue;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class ImageDownloader implements HttpItemListener {
	private static ImageDownloader ImageDownloader_sharedInstance = null;
	
	private HttpQueue normalQueue = new HttpQueue();
	private HttpItem http = null;
	private Vector<String> need_to_download = new Vector<String>();
	private Dictionary<String, Bitmap> downloaded = new Hashtable<String, Bitmap>();
	
	
	public Bitmap downloadImage(String url) {
		if (url != null) {
			if (downloaded.get(url) == null) {
				if (http == null) {
					String logo_url = url;
					Vector<Dictionary<String, String>> servers =  LoginServer.sharedInstance().data;
					for (int i = 0; i < servers.size(); i++) {
						Dictionary<String, String> dic = servers.elementAt(i);
						if (dic.get("connected") != null) {
							logo_url = dic.get("url") + url;
							break;
						}
					}
					
					http = normalQueue.get(logo_url, this, url, false);
				} else {
					need_to_download.removeElement(url);
					need_to_download.addElement(url);
				}
			} else {
				return downloaded.get(url);
			}
		}
		return null;
	}

	public static ImageDownloader sharedInstance() {
		if (ImageDownloader_sharedInstance == null) {
			ImageDownloader_sharedInstance = new ImageDownloader();
		}
		return ImageDownloader_sharedInstance;
	}

	public void reqeuestFinished(byte[] byteArray, Element xml,
			boolean successfull, Object param) {
		String url = (String)param;
		http = null;
		need_to_download.removeElement(url);
		Bitmap bitmap = null;
		if (successfull) {
			try {
				bitmap = BitmapFactory.decodeByteArray(byteArray, 0,
	                    byteArray.length);
			} catch (Exception e) {
				
			}
		}
		
		if (bitmap != null) {
			downloaded.put(url, bitmap);
			AppDelegate.sharedInstance().postNotification(ImageDownloaderNotificationListener.class, null, url);
		}
		
		continueQueue();
	}
	
	private void continueQueue() {
		if (need_to_download.size() > 0) {
			String address = need_to_download.elementAt(0);
			need_to_download.removeElementAt(0);
			downloadImage(address);
		}
	}
}
